package pkg

import (
	"context"
	"github.com/gin-gonic/gin"
)

type contextKey string

type GoroutineContextManager struct {
	GlobalGinContextKey contextKey
}

var GCM = &GoroutineContextManager{
	GlobalGinContextKey: "ppw_gin_context",
}

func (gcm *GoroutineContextManager) SetContext(ctx *gin.Context) {
	oldCtx := ctx.Request.Context()
	newCtx := context.WithValue(oldCtx, gcm.GlobalGinContextKey, ctx)
	ctx.Request = ctx.Request.WithContext(newCtx)
}

func (gcm *GoroutineContextManager) GetContext(ctx context.Context) (*gin.Context, bool) {
	if ctx == nil {
		return nil, false
	}
	ginCtx, ok := ctx.Value(gcm.GlobalGinContextKey).(*gin.Context)
	return ginCtx, ok
}
